/**
 * Copyright (c) 2005-2016, yinwer81 (yinwer81@aliyun.com)
 *
 * Licensed under the Apache License, Version 2.0
 */
package com.nozturn.throne.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSON;
import com.nozturn.throne.Constants;
import com.nozturn.throne.entity.Status;

public class Oauth2Filter implements Filter {

    private Logger logger = LoggerFactory.getLogger(Oauth2Filter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;

        OAuthAccessResourceRequest oauthRequest = null;
        try {
            // 构建OAuth资源请求，从queryString中获取参数
            oauthRequest = new OAuthAccessResourceRequest((HttpServletRequest) request, ParameterStyle.QUERY);
            // 构建OAuth资源请求，从HttpHead头中获取参数
            // OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest((HttpServletRequest) request, ParameterStyle.HEADER);
        } catch (OAuthSystemException ose) {
            logger.error("error trying to access oauth server", ose);
        } catch (OAuthProblemException ope) {
            logger.error("error trying to construct oauth access resource request", ope);
            try {
                oAuthFaileResponse(res);
            } catch (OAuthSystemException ose) {
                logger.error("error trying to access oauth server", ose);
            }
        }
        if (oauthRequest == null)
            return;

        String accessToken = null;
        try {
            accessToken = oauthRequest.getAccessToken();
        } catch (OAuthSystemException ose) {
            logger.error("error trying to get access token", ose);
        }
        if (accessToken == null)
            return;

        // 验证accessToken令牌
        if (!checkAccessToken(accessToken)) {
            /**
             * 如果不存在/过期了，返回未验证错误，需重新验证<br />
             * 
             * 客户端在此种情况下，应拿授权码换取accessToken令牌<br />
             * 1. 客户端则应引导用户登录，如果服务器端返回授权码不存在（用户在服务器端删除授权的情况），应引导用户再次授权<br />
             * 2. 客户端则应引导用户登录，如果服务器端返回授权码存在，获取accessToken令牌
             */
            try {
                oAuthFaileResponse(res);
            } catch (OAuthSystemException ose) {
                logger.error("error trying to build oauth failed response", ose);
                return;
            }
        }
        chain.doFilter(request, response);

    }

    /**
     * oAuth认证失败时的输出
     * 
     * @param res
     * @throws OAuthSystemException
     * @throws IOException
     */
    private void oAuthFaileResponse(HttpServletResponse res) throws OAuthSystemException, IOException {

        OAuthResponse oauthResponse = OAuthRSResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED).setRealm(Constants.RESOURCE_SERVER_NAME)
                .setError(OAuthError.ResourceResponse.INVALID_TOKEN).buildHeaderMessage();
        // HttpHeaders responseHeaders = new HttpHeaders();
        // responseHeaders.add("Content-Type", "application/json;charset=utf-8");
        res.setContentType("application/json; charset=utf-8");
        res.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
        PrintWriter writer = res.getWriter();
        writer.write(JSON.toJSONString(new Status(HttpStatus.UNAUTHORIZED.value(), Constants.INVALID_ACCESS_TOKEN)));
        writer.flush();
        writer.close();
    }

    /**
     * 验证accessToken，应在Filter中访问Cache，然后验证accessToken是否在Cache中存在来判断
     * 
     * @param accessToken
     * @return
     * @throws IOException
     */
    private boolean checkAccessToken(String accessToken) throws IOException {
        URL url = new URL(Constants.CHECK_ACCESS_CODE_URL + accessToken);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.disconnect();
        return HttpServletResponse.SC_OK == conn.getResponseCode();
    }

    @Override
    public void destroy() {
        // nothing
    }

}
